package com.aibili.contoller.api;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aibili.common.SMessageUtil;
import com.aibili.pojo.BlackList;
import com.aibili.pojo.HobbyInfo;
import com.aibili.pojo.ReportInfo;
import com.aibili.pojo.UserAnonymous;
import com.aibili.pojo.UserInfo;
import com.aibili.service.AnonymousService;
import com.aibili.service.ChatService;
import com.aibili.service.CheckSumBuilder;
import com.aibili.service.FileService;
import com.aibili.service.GiftService;
import com.aibili.service.MomentService;
import com.aibili.service.UserInfoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daoshun.common.CommonUtils;
import com.daoshun.common.DsConstant;
import com.daoshun.common.HttpRequest;
import com.daoshun.exception.CustomException;

@Controller
@RequestMapping("/api/user")
public class ApiUserContoller extends ApiBaseContoller {
	@Resource
	private UserInfoService userInfoService;

	@Resource
	private FileService fileService;

	@Resource
	private MomentService momentService;

	@Resource
	private GiftService giftService;

	@Resource
	private AnonymousService anonymousService;
	
	@Resource
	private ChatService chatService;

	/**
	 * 登录
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login", produces = "application/json; charset=UTF-8")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String phone = request.getParameter("phone");
			String password = request.getParameter("password");
			CommonUtils.validateEmpty(phone);
			CommonUtils.validateEmpty(password);
			UserInfo info = userInfoService.login(phone);
			if (info == null) {
				return DsConstant.NO_USER;
			} else if (!info.getPassword().equals(password)) {
				return DsConstant.PASSERROR;
			} else if(info.getIs_seale()!=0){
				return DsConstant.BLACK;
			}else {
				List<UserInfo> user_list = chatService.getfansListByUser(info.getId());
				int fansamount = user_list.size();
				info.setFans_num(fansamount);//粉丝数量
				List<UserInfo> auser_list = chatService.getAttentionListByUser(info.getId());
				int amount = auser_list.size();
				info.setAttention_num(amount);//关注数量
				userInfoService.updateUserInfo(info);
				map.put("user", info);
				map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				return toJson(map);
			}
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}

	/**
	 * 注册
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/register", produces = "application/json; charset=UTF-8")
	public String register(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String phone = request.getParameter("moblie");
			String vcode = request.getParameter("vcode");
			String gender = request.getParameter("gender");
			String password = request.getParameter("password");
			CommonUtils.validateEmpty(phone);
			CommonUtils.validateEmpty(password);
			CommonUtils.validateEmpty(vcode);
			CommonUtils.validateEmpty(gender);
			// 用户是否存在
			UserInfo user = userInfoService.login(phone);
			if (user != null) {
				return DsConstant.USER_EXIST;
			} else {
				long count = userInfoService.getPhoneCode(phone, vcode);
				if (count == 0) {
					return DsConstant.VCODEERROR;
				} else {

					CloseableHttpClient httpclient = HttpClients.createDefault();
					HttpPost httpPost = new HttpPost(DsConstant.ENTEASE_LOGIN_ACTION);

					String appKey = DsConstant.APPKEY;
					String appSecret = DsConstant.APPSECRET;
					String nonce = CommonUtils.getRandomString(10);
					String curTime = String.valueOf((new Date()).getTime() / 1000L);
					String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);// 参考
																								// 计算CheckSum的java代码

					// 设置请求的header
					httpPost.addHeader("AppKey", appKey);
					httpPost.addHeader("Nonce", nonce);
					httpPost.addHeader("CurTime", curTime);
					httpPost.addHeader("CheckSum", checkSum);
					httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

					// 设置请求的参数
					List<NameValuePair> nvps = new ArrayList<NameValuePair>();
					nvps.add(new BasicNameValuePair("accid", phone));
					httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

					// 执行请求
					HttpResponse response1 = httpclient.execute(httpPost);
					String entitystr = EntityUtils.toString(response1.getEntity(), "utf-8");
					JSONObject entityJson = JSONObject.parseObject(entitystr);
					int code = entityJson.getInteger("code");
					if (code == 200) {
						String entity = entityJson.getString("info");
						JSONObject infoJson = JSONObject.parseObject(entity);
						String accid = infoJson.getString("accid");
						String token = infoJson.getString("token");

						UserInfo info = userInfoService.addUserInfo(accid, password, gender, token);
						map.put("user", info);
						map.putAll(DsConstant.SUCCESS_RESULT_MAP);
						return toJson(map);
					} else {
						String message = entityJson.getString("desc");
						if (message.equals("already register")) {
							return DsConstant.USER_EXIST;
						} else {
							return DsConstant.EXCEPTION;
						}
					}
				}
			}

		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 获得验证码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getvcode", produces = "application/json; charset=UTF-8")
	public String getVcode(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String phone = request.getParameter("moblie");
			CommonUtils.validateEmpty(phone);

			String vcode = userInfoService.getVcode(phone);
			
			// 发送短信验证码
			String responseStr = SMessageUtil.batchSend(phone, "您好，您的验证码："+vcode+"，5分钟内有效");
			int index = responseStr.indexOf(",");
			if (index != 0) {
				if(responseStr.substring(index+1).startsWith("0")) {
					map.put("vcode", vcode);
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
					return JSON.toJSONString(map);
				}
			}
			return DsConstant.PHONELATER;
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 修改用户信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/edituser", produces = "application/json; charset=UTF-8")
	public String edituser(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			String mobile = request.getParameter("mobile");
			String idcard = request.getParameter("idcard");
			String realname = request.getParameter("real_name");
			// 如果idcard 或者realname 不为空，则进行身份验证
			if (!CommonUtils.isEmptyString(idcard) || !CommonUtils.isEmptyString(realname)) {
				long timestamp = System.currentTimeMillis();
				double random = Math.random();
				String sign =  CommonUtils.MD5(DsConstant.KUAIGE_PASSWORD + timestamp + random);
				
				// 固定字段数据
				BasicNameValuePair singParams = new BasicNameValuePair("sign", sign);
				BasicNameValuePair accountParams = new BasicNameValuePair("account", DsConstant.KUAIGE_ACCOUNT);
				BasicNameValuePair timestampParams = new BasicNameValuePair("timestamp", String.valueOf(timestamp));
				BasicNameValuePair randomParams = new BasicNameValuePair("random", String.valueOf(random));

				// 业务数据
				BasicNameValuePair dataParams = new BasicNameValuePair("data", "{\"idCard\":\""+idcard+"\",\"name\":\""+realname+"\"}");
				String resp = HttpRequest.postKuaige(DsConstant.KUAIGE_ID_URL, singParams, accountParams, timestampParams, randomParams, dataParams);
				
				JSONObject jsonObj = JSONObject.parseObject(resp);
				int status = jsonObj.getIntValue("status");
				if (status == 0) {
					String val = jsonObj.getString("data");
					switch (val) {
					case "1":
						UserInfo user = userInfoService.getById(CommonUtils.parseLong(user_id, 0));
						if (user != null) {
							user.setIdcard(idcard);
							user.setReal_name(realname);
							userInfoService.updateUserInfo(user);
							map.put("user", user);
							map.putAll(DsConstant.SUCCESS_RESULT_MAP);
							return toJson(map);
						}
						return DsConstant.NO_USER;
					case "2":
						return DsConstant.WRONG_IDENTITY;
					default:
						return DsConstant.WRONG_IDENTITY;
					}
	 			} else {
					return DsConstant.WRONG_IDENTITY;
				}
			} else {
				String username = request.getParameter("user_name");
				String level = request.getParameter("level");
				String birthday = request.getParameter("birthday");
				String income = request.getParameter("income");
				String height = request.getParameter("height");
				String location = request.getParameter("location");
				String loveactivity = request.getParameter("love_activity");
				String hobbies = request.getParameter("hobbies");
				String adepthings = request.getParameter("adepthings");
				String gender = request.getParameter("gender");
				String signature = request.getParameter("signature");
				String yx_reg = request.getParameter("yx_reg");
				String password = request.getParameter("password");
				String paypassword = request.getParameter("paypassword");
				String portrait = getorcaFilePath(request);
				UserInfo info1 = userInfoService.getMobile(mobile, CommonUtils.parseLong(user_id, 0));
				if (info1 != null) {
					return DsConstant.MOBLIE_EXIST;
				} else {
					UserInfo info = userInfoService.updateUserInfo(user_id, mobile, username, portrait, level, idcard,
							birthday, income, height, location, loveactivity, hobbies, adepthings, gender, realname,
							yx_reg,signature,password,paypassword);
					List<UserInfo> auser_list = chatService.getAttentionListByUser(info.getId());
					int amount = auser_list.size();
					info.setAttention_num(amount);
					map.put("user", info);
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
					return toJson(map);
				}
			}
			
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 
	 * @Description 用戶列表
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", produces = "application/json; charset=UTF-8")
	public String list(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			String keywords = request.getParameter("keywords");
			String type1 = request.getParameter("type");
			String gender = request.getParameter("gender");
			int sex = CommonUtils.parseInt(gender, 0);
			int type = CommonUtils.parseInt(type1, 0);
			String location = request.getParameter("location");
			String page = request.getParameter("page");
			if (CommonUtils.isEmptyString(page) || page.equals("0")) {
				page = "1";
			}
			String longitude = "";
			String latitude = "";

			if (type == 1) {
				// 需要按距离排序
				if (CommonUtils.isEmptyString(location)) {
					return DsConstant.EXCEPTION;
				} else {
					String[] strs = location.split(",");
					if (strs.length == 2) {
						longitude = strs[0];
						latitude = strs[1];
					} else {
						return DsConstant.EXCEPTION;
					}
				}
			}

			List<UserInfo> list = userInfoService.getUserList(keywords, type, CommonUtils.parseDouble(longitude, 0),
					CommonUtils.parseDouble(latitude, 0), CommonUtils.parseInt(page, 1),
					CommonUtils.parseLong(user_id, 0), sex);
			map.put("user_list", list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}

	/**
	 * 修改用户匿名信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anonymous", produces = "application/json; charset=UTF-8")
	public String anonymous(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("id");
			String nick_name = request.getParameter("nick_name");
			CommonUtils.validateEmpty(user_id);
			long uid = CommonUtils.parseLong(user_id, 0);
			String intro = request.getParameter("intro");
			String portrait = "";
			// 如果有性别传过来，则头像则是服务器上的相对应性别的头像，
			String gender = request.getParameter("gender");
			if (!CommonUtils.isEmptyString(gender)) {
				if ("0".equals(gender)) {
					portrait = "default/anonymous_men_icon.png";
				} else {
					portrait = "default/anonymous_women_icon.png";
				}
			} else {
				portrait = getorcaFilePath(request);
			}

			boolean flag = false; // 注不注册环信
			UserAnonymous anonymous = anonymousService.getByUserid(uid);
			if (anonymous == null) {
				flag = true; // 没有匿名账号的 都去注册匿名信息
			}

			// nick_name 不为空 注册
			if (!CommonUtils.isEmptyString(nick_name)) {
				flag = true;
			}
			// 头像不为空 注册
			if (!CommonUtils.isEmptyString(portrait)) {
				flag = true;
			}

			if (flag) {
				// 获得注册的环信id
				String anon_id = anonymousService.getAnonymousid();
				// 获得注册的环信密码
				String anon_pass = CommonUtils.getRandomString(10);
				String pass = CommonUtils.MD5(anon_pass);

				// 注册
				String backstr = anonymousService.register(anon_id, pass, nick_name);

				if (!backstr.equals("")) {
					JSONObject backjson = JSONObject.parseObject(backstr);
					String error = backjson.getString("error");
					if (error == null) {
						if (anonymous != null) {

							// 删除该环信id
							// anonymousService.deleteAnonymous_id(anonymous2.getAnonymous_id());

							anonymous.setAnonymous_id(anon_id);
							anonymous.setPassword(pass);
							if (!CommonUtils.isEmptyString(nick_name)) {
								anonymous.setNick_name(nick_name);
							}

							if (!CommonUtils.isEmptyString(portrait)) {
								anonymous.setPortrait(portrait);
							}

							if (!CommonUtils.isEmptyString(intro)) {
								anonymous.setIntro(intro);
							}

							anonymousService.update(anonymous);

							map.put("anonymous", anonymous);
						} else {
							UserAnonymous anonymous1 = new UserAnonymous();
							anonymous1.setAnonymous_id(anon_id);
							anonymous1.setUser_id(uid);
							anonymous1.setPassword(pass);
							anonymous1.setNick_name(nick_name);
							anonymous1.setPortrait(portrait);
							anonymous1.setIntro(intro);

							anonymousService.add(anonymous1);
							map.put("anonymous", anonymous1);
						}

						return toSuccessJson(map);
					} else {
						return DsConstant.EXCEPTION;
					}

				} else {
					return DsConstant.EXCEPTION;
				}
			} else {
				// 只有单个宣言的情况下，才修改
				if (!CommonUtils.isEmptyString(intro)) {
					anonymous.setIntro(intro);
				}

				anonymousService.update(anonymous);
				map.put("anonymous", anonymous);
				return toSuccessJson(map);
			}

		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 匿名用户信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anonymous_list", produces = "application/json; charset=UTF-8")
	public String anonymousList(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			String page = request.getParameter("page");
			String location = request.getParameter("location");
			CommonUtils.validateEmpty(location);
			String longitude = "";
			String latitude = "";
			String[] strs = location.split(",");
			if (strs.length == 2) {
				longitude = strs[0];
				latitude = strs[1];
			}
			if (CommonUtils.isEmptyString(page) || page.equals("0")) {
				page = "1";
			}
			List<UserAnonymous> list = userInfoService.userAnonymous(page, longitude, latitude, user_id);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			map.put("user_list", list);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 守护神
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/guardian", produces = "application/json; charset=UTF-8")
	public String guardian(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String id = request.getParameter("user_id");
			String page = request.getParameter("page");
			if (CommonUtils.isEmptyString(page) || page.equals("0")) {
				page = "1";
			}
			CommonUtils.validateEmpty(id);
			List<UserInfo> list = userInfoService.userGuard(CommonUtils.parseLong(id, 0),
					CommonUtils.parseInt(page, 1));
			map.put("user_list", list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 忘记密码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/changepass", produces = "application/json; charset=UTF-8")
	public String changePass(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String phone = request.getParameter("moblie");
			String vcode = request.getParameter("vcode");
			String password = request.getParameter("password");
			String paypassword = request.getParameter("paypassword");
			CommonUtils.validateEmpty(phone);
			//CommonUtils.validateEmpty(password);
			CommonUtils.validateEmpty(vcode);
			long count = userInfoService.getPhoneCode(phone, vcode);
			if (count == 0) {
				return DsConstant.VCODEERROR;
			} 
			if(!CommonUtils.isEmptyString(password)) {
				UserInfo info = userInfoService.changePassUser(phone, password);
				if (info == null) {
					return DsConstant.NO_USER;
				} else {
					map.put("user", info);
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
					
				}
			}
			if (!CommonUtils.isEmptyString(paypassword)) {
				UserInfo info = userInfoService.changePayPassword(phone,paypassword);
				if (info == null) {
					return DsConstant.NO_USER;
				} else {
					map.put("user", info);
					map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				}
			}
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 取活动、兴趣爱好、擅长的列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/hobbies", produces = "application/json; charset=UTF-8")
	public String hobbies(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			List<HobbyInfo> hobby_list = userInfoService.getHobbyList();
			map.put("hobby_list", hobby_list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 搭讪列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/accost", produces = "application/json; charset=UTF-8")
	public String accost(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			String keywords = request.getParameter("keywords");
			String page = request.getParameter("page");
			String location = request.getParameter("location");
			if (CommonUtils.isEmptyString(page) || page.equals("0")) {
				page = "1";
			}
			String longitude = "";
			String latitude = "";
			if (!CommonUtils.isEmptyString(location)) {
				String[] strs = location.split(",");
				if (strs.length == 2) {
					longitude = strs[0];
					latitude = strs[1];
				}
			}
			List<UserInfo> list = userInfoService.getUserAccost(keywords, CommonUtils.parseDouble(longitude, 0),
					CommonUtils.parseDouble(latitude, 0), CommonUtils.parseInt(page, 0),
					CommonUtils.parseLong(user_id, 0));
			map.put("user_list", list);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}

	/**
	 * 
	 * @Description 用户详情的四个图片信息
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/indexlist", produces = "application/json; charset=UTF-8")
	public String indexlist(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);

			long uid = CommonUtils.parseLong(user_id, 0);

			// 通过 user_id 查找有图片的动态
			List<String> momentstrs = momentService.getIndexMoment(uid);
			List<String> momentlist = new ArrayList<>();
			if (momentstrs != null && momentstrs.size() > 0) {
				String str = momentstrs.get(0);
				for (int i = 1, len = momentstrs.size(); i < len; i++) {
					str += "," + momentstrs.get(i);
				}
				momentlist = Arrays.asList(str.split(","));
				if (momentlist.size() > 3) {
					momentlist = momentlist.subList(0, 3);
				} else {
					momentlist = momentlist.subList(0, momentlist.size());
				}
				

			}
			map.put("moment_list", momentlist);

			// 通过 user_id 查找 礼物
			List<String> giftstrs = giftService.getIndexGift(uid);
			map.put("gift_list", giftstrs);

			// 通过 user_id 查找情感中心
			List<String> sendstrs = giftService.getIndexSend(uid);
			map.put("send_list", sendstrs);

			// 通过 user_id 查找守护神
			List<String> userstrs = userInfoService.getIndexUser(uid);
			map.put("guardian_list", userstrs);

			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}

	/**
	 * 
	 * @Description 通过用户 id 获取用户信息
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userinfo", produces = "application/json; charset=UTF-8")
	public String userinfo(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String from_id = request.getParameter("from_id");
			String to_id = request.getParameter("to_id");
			CommonUtils.validateEmpty(from_id);
			CommonUtils.validateEmpty(to_id);
			UserInfo info = userInfoService.getByTwoid(CommonUtils.parseLong(from_id, 0),
					CommonUtils.parseLong(to_id, 0));
			if (info != null) {
//				List<UserInfo> user_list = chatService.getfansListByUser(info.getId());
//				int fansamount = user_list.size();
//				info.setFans_num(fansamount);//粉丝数量
//				List<UserInfo> auser_list = chatService.getAttentionListByUser(info.getId());
//				int amount = auser_list.size();
//				info.setAttention_num(amount);//关注数量
				userInfoService.updateUserInfo(info);
				map.put("userinfo", info);
				map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				return toJson(map);
			} else {
				return DsConstant.NO_USER;
			}

		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}

	/**
	 * 
	 * @Description 获取匿名用户信息
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/anonymousinfo", produces = "application/json; charset=UTF-8")
	public String anonymousinfo(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			UserAnonymous info = userInfoService.getAnonymousByUserid(CommonUtils.parseLong(user_id, 0));
			if (info != null) {
				map.put("anonymous", info);
				map.putAll(DsConstant.SUCCESS_RESULT_MAP);
				return toJson(map);
			} else {
				return DsConstant.NO_USER;
			}

		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}
	
	/**
	 * 粉丝列表
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/fanslist", produces = "application/json; charset=UTF-8")
	public String fanslist(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			List<UserInfo> user_list = chatService.getfansListByUser(CommonUtils.parseLong(user_id, 0));
			int amount = user_list.size();
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			map.put("user_list", user_list);
			map.put("amount", amount);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}

	/**
	 * 黑名单列表
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/myblacklist", produces = "application/json; charset=UTF-8")
	public String myblacklist(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			List<UserInfo> user_list = chatService.getblackListByUser(CommonUtils.parseLong(user_id, 0));
			int amount = user_list.size();
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			map.put("user_list", user_list);
			map.put("amount", amount);
			return toJson(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}
	}
	
	/**
	 * 举报用户
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/accuse", produces = "application/json; charset=UTF-8")
	public String accuse(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			long userid = CommonUtils.parseLong(user_id, 0);
			String mine_id = request.getParameter("mine_id");
			CommonUtils.validateEmpty(mine_id);
			long mineid = CommonUtils.parseLong(mine_id, 0);
			String sccuse_content = request.getParameter("sccuse_content");
			ReportInfo report = new ReportInfo();
			report.setUser_id(userid);
			report.setMine_id(mineid);
			report.setContent(sccuse_content);
			report.setAddtime(new Date());
			chatService.accuse(report);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return JSON.toJSONString(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}
	
	/**
	 * 加入黑民单
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addtoblack", produces = "application/json; charset=UTF-8")
	public String addtoblack(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_mobile = request.getParameter("user_mobile");
			String black_mobile = request.getParameter("black_mobile");
			CommonUtils.validateEmpty(user_mobile);
			CommonUtils.validateEmpty(black_mobile);
			UserInfo user = userInfoService.getUserByPhone(user_mobile);
			UserInfo blackuser = userInfoService.getUserByPhone(black_mobile);
			long userid = user.getId();
			long blackid = blackuser.getId();
			BlackList hasblack = chatService.getbalck(userid,blackid);
			if (hasblack != null) {
				return DsConstant.HASBLACK;
			}
			BlackList black = new BlackList();
			black.setUser_id(userid);
			black.setTo_id(blackid);
			chatService.addtoblack(black);
			chatService.removeattention(userid,blackid);//从关注和粉丝列表中移出
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return JSON.toJSONString(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}
	
	
	/**
	 * 移出黑名单
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/removefromblack", produces = "application/json; charset=UTF-8")
	public String removefromblack(HttpServletRequest request, HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			request.setCharacterEncoding("utf-8");
			String user_id = request.getParameter("user_id");
			CommonUtils.validateEmpty(user_id);
			long userid = CommonUtils.parseLong(user_id, 0);
			String black_id = request.getParameter("black_id");
			CommonUtils.validateEmpty(black_id);
			long blackid = CommonUtils.parseLong(black_id, 0);
			chatService.removefromblack(userid,blackid);
			map.putAll(DsConstant.SUCCESS_RESULT_MAP);
			return JSON.toJSONString(map);
		} catch (CustomException e) {
			return e.getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			return DsConstant.EXCEPTION;
		}

	}
}
